package cc.iotkit.manager.controller.adminMiniApp;

import cc.iotkit.common.api.Request;
import cc.iotkit.common.enums.DeviceType;
import cc.iotkit.common.enums.ErrCode;
import cc.iotkit.common.enums.UserType;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.web.core.BaseController;
import cc.iotkit.data.util.TokenUtil;
import cc.iotkit.manager.dto.vo.login.MiniAdminLoginBody;
import cc.iotkit.manager.dto.vo.login.MiniAdminLoginVo;
import cc.iotkit.manager.model.vo.miniAdminLoginUserBo;
import cc.iotkit.manager.service.ISysDistributorService;
import cc.iotkit.model.system.SysDistributor;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = {"后台管理小程序登录管理"})
@Slf4j
@RestController
@RequestMapping("/miniAdmin")
public class MiniAdminLoginController extends BaseController {

    @Autowired
    private ISysDistributorService sysDistributorService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private ObjectMapper objectMapper;

    @ApiOperation("登录")
    @PostMapping("/login")
    public MiniAdminLoginVo login( @RequestBody Request<MiniAdminLoginBody> body) throws Exception {
        MiniAdminLoginVo loginVo = new MiniAdminLoginVo();
        // 生成令牌
        SysDistributor sysDistributor =  sysDistributorService.loadByAcctAndPass(body.getData().getAcct(),body.getData().getPassword());

        if(ObjectUtil.isEmpty(sysDistributor)){
            throw new BizException(ErrCode.USER_NOT_FOUND);
        }

        miniAdminLoginUserBo loginUser = new miniAdminLoginUserBo();
        loginUser.setUserId(sysDistributor.getId());
        loginUser.setUsername(sysDistributor.getAcct());
        loginUser.setUserType(UserType.MINI_ADMIN_USER.getUserType());
        LoginHelper.loginByDevice(loginUser, DeviceType.MINIADMIN);
        String token = StpUtil.getTokenValue();
        loginVo.setToken(token);
        return loginVo;
    }
}
